package com.uyayo.oms.system.controller;

import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.common.exception.CodeMultipleException;
import com.uyayo.framework.common.exception.ParentNotFoundException;
import com.uyayo.framework.message.model.Result;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.oms.system.vo.SysDictionaryDataVO;
import com.uyayo.oms.system.vo.SysDictionaryVO;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.system.config.entity.SysDictionary;
import com.uyayo.system.config.entity.SysDictionaryData;
import com.uyayo.system.config.service.SysDictionaryService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * 
 * Title: DictionaryController
 * Description:数据字典的controller
 * Company: www.lelekeji.com
 *
 * @author 乐乐科技.胡逢君
 * @date 2015-4-13下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/system/config/dictionary")
public class SysDictionaryController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired SysDictionaryService sysDictionaryService;
	
	@Autowired
	private ParamBiz paramBiz;

	@Autowired
	private MessageSource messageSource;
	/**
	 * 进入数据字典主页面
	 */
	@RequestMapping(value="index",method=RequestMethod.GET)
	@RequiresPermissions("system:config:dictionary:index")
	@MethodName(value="系统管理->系统配置->数据字典管理",type=1)
	public String index() {
		return paramBiz.getManagerTemplatesPrefix()+"system/config/dictionary/index";
	}

	@ResponseBody
	@RequestMapping(value="grid",method=RequestMethod.GET)
	@RequiresPermissions("system:config:dictionary:grid")
	@MethodName(value="系统管理->系统配置->全局参数管理->查询列表",type=2)
	public PageResult<SysDictionary> grid(@RequestParam(value = "offset",required = false, defaultValue = "1") Integer offset, //第多少行之后开始
										  @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize, String sort, String order, SysDictionary sysDictionary) throws Exception {
		PageBean<SysDictionary> pageBean=new PageBean<>();
		try {
			pageBean = sysDictionaryService.selectSysDictionaryByPage((offset / pageSize) + 1, pageSize,sort,order,sysDictionary);
		} catch (Exception e) {
			e.printStackTrace();
		}
		PageResult<SysDictionary> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;

	}

	/**
	 * 进入全局参数查看页面
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="系统管理->系统配置->全局参数管理->查看",type=2)
	@RequiresPermissions("system:config:dictionary:view")
	public ModelAndView show(ModelAndView modelAndView,Long id) {
		SysDictionary sysDictionary = new SysDictionary();
		try {
			sysDictionary = sysDictionaryService.getDictionaryById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.addObject("sysDictionary",sysDictionary);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/dictionary/view");
		return modelAndView;
	}

	/**
	 * 进入添加全局参数页面
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	@RequiresPermissions("system:config:dictionary:add")
	public ModelAndView add(ModelAndView modelAndView) {

		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/dictionary/add");
		return modelAndView;
	}

	/**
	 * 新建一个全局参数
	 */
	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@RequiresPermissions("system:config:dictionary:add")
	@MethodName(value="系统管理->系统配置->全局参数管理->保存全局参数",type=2)
	synchronized public Result add(@Validated SysDictionaryVO sysDictionaryVo , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			SysDictionary test = sysDictionaryService.getDictionaryByCode(sysDictionaryVo.getCode());
			if(test!=null){
				return Result.errorAndMsg("保存失败，编码已存在！");
			}
			SysDictionary sysDictionary = new SysDictionary();
			sysDictionary.setCode(sysDictionaryVo.getCode());
			sysDictionary.setName(sysDictionaryVo.getName());
			sysDictionary.setType(sysDictionaryVo.getType());
			sysDictionary.setStatus(sysDictionaryVo.getStatus());
			sysDictionary.setSeq(sysDictionaryVo.getSeq());
			sysDictionary.setDescription(sysDictionaryVo.getDescription());
			sysDictionary.setCreatedTime(new Date());
			sysDictionary.setRemark(sysDictionaryVo.getRemark());
			sysDictionaryService.insertDictionary(sysDictionary);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorAndMsg("保存失败！");
		}
		return Result.successAndMsg("保存成功！");
	}


	/**
	 * 进入角色修改页面
	 */
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("system:config:dictionary:update")
	public ModelAndView update(ModelAndView modelAndView,Long id) {
		SysDictionary sysDictionary = new SysDictionary();
		try {
			sysDictionary = sysDictionaryService.getDictionaryById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.addObject("sysDictionary",sysDictionary);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/dictionary/edit");
		return modelAndView;
	}

	/**
	 * 修改一个全局参数
	 */
	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@RequiresPermissions("system:config:dictionary:update")
	@MethodName(value="系统管理->系统配置->数据字典管理->修改",type=2)
	synchronized public Result update(@Validated SysDictionaryVO sysDictionaryVo , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}

			SysDictionary test = sysDictionaryService.getDictionaryByCode(sysDictionaryVo.getCode());
			if(test!=null && sysDictionaryVo.getId()==test.getId()){
				return Result.errorAndMsg("保存失败，编码已存在！");
			}
			SysDictionary sysDictionary = new SysDictionary();
			sysDictionary.setId(sysDictionaryVo.getId());
			sysDictionary.setCode(sysDictionaryVo.getCode());
			sysDictionary.setName(sysDictionaryVo.getName());
			sysDictionary.setType(sysDictionaryVo.getType());
			sysDictionary.setSeq(sysDictionaryVo.getSeq());
			sysDictionary.setDescription(sysDictionaryVo.getDescription());
			sysDictionary.setModifiedTime(new Date());
			sysDictionary.setRemark(sysDictionaryVo.getRemark());
			sysDictionaryService.updateDictionary(sysDictionary);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorAndMsg("保存失败！");
		}
		return Result.successAndMsg("保存成功！");
	}


	/**
	 * 删除数据字典
	 */
	@ResponseBody
	@RequiresPermissions("system:config:dictionary:delete")
	@RequestMapping(value="delete",method=RequestMethod.DELETE)
	@MethodName(value="系统管理->系统配置->数据字典管理->删除数据字典",type=2)
	public Result deleteDictionary(Long id) {
		if (id!=null) {
			try {
				int deleteCount = sysDictionaryService.deleteDictionary(id);
				if(deleteCount<=0){
					return Result.errorAndMsg("删除失败！");
				}
			} catch (Exception e) {
				e.printStackTrace();
				return Result.errorAndMsg("删除失败！");
			}
		}else{
			return Result.errorAndMsg("请选择需删除的记录！");
		}
		return Result.successAndMsg("删除成功！");
	}



	/**
	 * 获得数据字典treeGrid
	 */
	@ResponseBody
	@RequestMapping("treeGrid")
	@MethodName(value="系统管理->系统配置->数据字典管理->查询列表",type=2)
	public List<SysDictionary> treeGrid(SysDictionary dictionary) {
		return sysDictionaryService.selectSysDictionary(dictionary);
	}
	
	/**
	 * 获得数据字典treeGrid
	 */
	@ResponseBody
	@RequestMapping("data/treetable")
	@MethodName(value="系统管理->系统配置->数据字典管理->查询列表",type=2)
	public List<SysDictionaryData> dictionaryDataTreeGrid(SysDictionaryData sysDictionaryData) {
		return sysDictionaryService.selectSysDictionaryData(sysDictionaryData);
	}
	
	/**
	 * 进入数据字典主页面
	 */
	@RequestMapping(value="data/index",method=RequestMethod.GET)
	@MethodName(value="系统管理->系统配置->数据字典数据管理")
	public String dictionaryDataIndex(Model model,Integer dictionaryId,@RequestParam(value = "parentId",required = false, defaultValue = "0") Integer parentId) {
		model.addAttribute("parentId",parentId);
		model.addAttribute("dictionaryId",dictionaryId);
		return paramBiz.getManagerTemplatesPrefix()+"system/config/dictionary/data_index";
	}



	/**
	 * 进入添加全局参数页面
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping(value = "data/add", method = RequestMethod.GET)
	@RequiresPermissions("system:config:dictionary:data:add")
	public ModelAndView dataAdd(ModelAndView modelAndView) {
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/dictionary/data_add");
		return modelAndView;
	}

	/**
	 * 新建一个全局参数
	 */
	@ResponseBody
	@RequestMapping(value = "data/add", method = RequestMethod.POST)
	@RequiresPermissions("system:config:dictionary:data:add")
	@MethodName(value="系统管理->系统配置->字典数据管理->新增",type=2)
	synchronized public Result dataAdd(@Validated SysDictionaryDataVO sysDictionaryDataVO , Errors errors, HttpServletRequest request) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();

			SysDictionaryData sysDictionaryData = new SysDictionaryData();
			sysDictionaryData.setCode(sysDictionaryDataVO.getCode());
			sysDictionaryData.setName(sysDictionaryDataVO.getName());
			sysDictionaryData.setDictionaryId(sysDictionaryDataVO.getDictionaryId());
			sysDictionaryData.setParentId(sysDictionaryDataVO.getParentId());
			sysDictionaryData.setValue(sysDictionaryDataVO.getValue());
			sysDictionaryData.setType(sysDictionaryDataVO.getType());
			sysDictionaryData.setStatus(sysDictionaryDataVO.getStatus());
			sysDictionaryData.setSeq(sysDictionaryDataVO.getSeq());
			sysDictionaryData.setDescription(sysDictionaryDataVO.getDescription());
			sysDictionaryData.setCreatedBy(sysUser.getLoginname());
			sysDictionaryData.setCreatedTime(new Date());
			sysDictionaryData.setRemark(sysDictionaryDataVO.getRemark());
			sysDictionaryService.insertDictionaryData(sysDictionaryData);
		}catch (ParentNotFoundException e){
			String message = messageSource.getMessage("parent.not.found.error",new Object[]{}, request.getLocale());
			logger.error(message,e.getMessage());
			return Result.build(500,message);
		} catch (CodeMultipleException e){
			String message = messageSource.getMessage("code.multiple.error",new Object[]{}, request.getLocale());
			logger.error(message,e.getMessage());
			return Result.build(500,message);
		}catch(Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(500,message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

		return Result.successAndMsg(message);
	}

	/**
	 * 进入修改字典数据页面
	 * @param modelAndView ModelAndView
	 * @return ModelAndView
	 */
	@RequestMapping(value = "data/view", method = RequestMethod.GET)
	@RequiresPermissions("system:config:dictionary:data:view")
	public ModelAndView dataView(ModelAndView modelAndView,Long id) {
		SysDictionaryData sysDictionaryData = sysDictionaryService.selectDictionaryDataById(id);
		modelAndView.addObject("sysDictionaryData",sysDictionaryData);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/dictionary/data_view");
		return modelAndView;
	}

	/**
	 * 进入修改字典数据页面
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping(value = "data/update", method = RequestMethod.GET)
	@RequiresPermissions("system:config:dictionary:data:update")
	public ModelAndView dataUpdate(ModelAndView modelAndView,Long id) {
		SysDictionaryData sysDictionaryData = sysDictionaryService.selectDictionaryDataById(id);
		modelAndView.addObject("sysDictionaryData",sysDictionaryData);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/dictionary/data_update");
		return modelAndView;
	}


	/**
	 * 更新字典数据
	 */
	@ResponseBody
	@RequestMapping(value = "data/update", method = RequestMethod.POST)
	@RequiresPermissions("system:config:dictionary:data:update")
	@MethodName(value="系统管理->系统配置->字典数据管理->修改",type=2)
	public Result updateOrganization(@Validated SysDictionaryDataVO sysDictionaryDataVO , Errors errors, HttpServletRequest request) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}

			if (sysDictionaryDataVO.getId()==sysDictionaryDataVO.getParentId()) {
				String message = messageSource.getMessage("parent.self.error",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}

			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();

			SysDictionaryData sysDictionaryData = new SysDictionaryData();

			sysDictionaryData.setId(sysDictionaryDataVO.getId());
			sysDictionaryData.setCode(sysDictionaryDataVO.getCode());
			sysDictionaryData.setName(sysDictionaryDataVO.getName());
			sysDictionaryData.setDictionaryId(sysDictionaryDataVO.getDictionaryId());
			sysDictionaryData.setParentId(sysDictionaryDataVO.getParentId());
			sysDictionaryData.setValue(sysDictionaryDataVO.getValue());
			sysDictionaryData.setType(sysDictionaryDataVO.getType());
			sysDictionaryData.setStatus(sysDictionaryDataVO.getStatus());
			sysDictionaryData.setSeq(sysDictionaryDataVO.getSeq());
			sysDictionaryData.setDescription(sysDictionaryDataVO.getDescription());
			sysDictionaryData.setModifiedBy(sysUser.getLoginname());
			sysDictionaryData.setModifiedTime(new Date());
			sysDictionaryData.setRemark(sysDictionaryDataVO.getRemark());
			int updateCount = sysDictionaryService.updateDictionaryData(sysDictionaryData);
			if(updateCount<=0){
				String message = messageSource.getMessage("save.fail",new Object[]{}, request.getLocale());
				logger.info(message);
				return Result.build(400,message);
			}
			String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

			return Result.success(200,message);

		} catch (ParentNotFoundException e){
			String message = messageSource.getMessage("parent.not.found.error",new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.build(400,message);
		} catch (CodeMultipleException e){
			String message = messageSource.getMessage("code.multiple.error",new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.build(400,message);
		} catch(Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500,message);
		}
	}

	/**
	 * 删除记录
	 */
	@ResponseBody
	@RequiresPermissions("system:config:dictionary:data:delete")
	@RequestMapping(value="data/delete",method=RequestMethod.DELETE)
	@MethodName(value="系统管理->系统配置->数据字典管理->删除数据字典数据",type=2)
	public Result deleteDictionaryData(Long id) {
		if (id!=null) {
			try {
				int deleteCount = sysDictionaryService.deleteDictionaryData(id);
				if(deleteCount<=0){
					return Result.errorAndMsg("删除失败！");
				}
			} catch (Exception e) {
				e.printStackTrace();
				return Result.errorAndMsg("删除失败！");
			}
		}else{
			return Result.errorAndMsg("请选择需删除的记录！");
		}
		return Result.successAndMsg("删除成功！");

	}
	
}
